import machine
import ssd1306
from display import Display
from uart_handler import UartHandler
from math import pi
import time

# 调试模式开关
debug = True

# 等待USB-CDC初始化完成
time.sleep(0.5)

# 初始化I2C和OLED显示屏
i2c = machine.I2C(0, sda=machine.Pin(0), scl=machine.Pin(1))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)  # 可以根据需要改为32或64

# 初始化串口 (UART1: TX=GP4, RX=GP5)
uart = machine.UART(1, baudrate=115200,
                   tx=machine.Pin(4),
                   rx=machine.Pin(5))

# 创建显示和串口处理对象
display = Display(oled)
uart_handler = UartHandler(uart)

def debug_display():
    """调试模式下的显示函数"""
    value = 0
    step = 50  # 每次增加的值
    direction = 1  # 1表示增加，-1表示减少
    
    while True:
        # 更新显示
        display.update_meter(value)
        
        # 更新值
        value += step * direction
        
        # 在0-1000范围内往复变化
        if value >= 1000:
            direction = -1
        elif value <= 0:
            direction = 1
            
        time.sleep(0.1)  # 控制更新速度

def main():
    if debug:
        debug_display()
        return
    
    # 正常运行模式
    current_value = 0
    display.update_meter(current_value)
    
    # 状态监控变量
    last_data_time = time.time()
    status_led_state = True
    status_check_time = time.time()
    led_toggle_time = time.time()
    
    while True:
        current_time = time.time()
        
        # 检查是否有新数据
        if uart_handler.data_available():
            value = uart_handler.read_value()
            if value is not None and 0 <= value <= 1024:
                current_value = value
                last_data_time = current_time
                status_led_state = True
                display.update_meter(current_value, status_led_state)
        
        # 每0.5秒切换一次状态指示点
        if current_time - led_toggle_time >= 0.5:
            led_toggle_time = current_time
            status_led_state = not status_led_state
            display.update_meter(current_value, status_led_state)
        
        # 每5秒检查一次数据接收状态
        if current_time - status_check_time >= 5:
            status_check_time = current_time
            # 如果5秒内没有收到新数据
            if current_time - last_data_time >= 5:
                uart.write('Ready\n')
        
        # 适当延时，避免过于频繁刷新
        time.sleep(0.01)
                
if __name__ == '__main__':
    main() 